﻿using System.ComponentModel;
using System.Globalization;

namespace System.Lua.Converters
{
    /// <summary>
    /// Converts <see cref="DateTime"/> values to and from POSIX time strings.
    /// </summary>
    internal class PosixDateTimeConverter : LuaTypeConverter<DateTimeConverter>
    {
        private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        public override bool CanConvertTo(Type targetType)
        {
            if (targetType == typeof(string))
                return true;

            return base.CanConvertTo(targetType);
        }

        public override object ConvertTo(object value, Type targetType)
        {
            if (targetType == typeof(string) && value is DateTime)
                return Math.Floor(((DateTime)value - Epoch).TotalSeconds).ToString(CultureInfo.InvariantCulture);

            return base.ConvertTo(value, targetType);
        }

        public override bool CanConvertFrom(Type sourceType)
        {
            if (sourceType == typeof(Double))
                return true;
            
            return base.CanConvertFrom(sourceType);
        }

        public override object ConvertFrom(object value)
        {
            if (value is Double)
                return Epoch.AddSeconds((double)value);

            return base.ConvertFrom(value);
        }

        /// <summary>
        /// Gets a value indicating whether the string returned by the converter is a valid Lua
        /// literal.
        /// </summary>
        public override bool ReturnsLiteral
        {
            get { return true; }
        }
    }
}